package game;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import net.Communications;

public class Game {
   
   private Maze maze;
   private String n = System.getProperty("line.separator");
   private List<Player> highScore;

   public Game(String entryName) {
      highScore = new ArrayList<Player>();
      maze = new Maze(entryName);
      new Communications(this);
   }
   
   /**
    * Adds a player to the game
    */
   public Player addPlayer(String name) {
      Player p = new Player(name, maze.getEntry());
      return p;
   }

   /**
    * Adds a score to highscore (sorted)
    */
   public synchronized void addScore(Player player) {
      int index = 0;
      if (highScore.size() > 0) {
         for (Iterator<Player> it = highScore.iterator(); it.hasNext(); ) {
            Player p = it.next();
            if (player.getCount() < p.getCount()) {
               index =  highScore.indexOf(p);
               break;
            }
         }
      }
      highScore.add(index, player);
   }
   
   /**
    * Gets the highscore in string formatted:
    * turns name
    * turns name
    */
   public String getHighScoreAsString() {
      StringBuffer strbfr = new StringBuffer();
      for (Player p : highScore) {
         strbfr.append(p.getCount() + " " + p.toString() + n);
      }
      return strbfr.toString();
   }
   
   public Maze getMaze() {
      return maze;
   }
 
}
